package informed.io;

import informed.matrix.SparseVector;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

import cern.colt.matrix.DoubleMatrix2D;
import cern.colt.matrix.impl.DenseDoubleMatrix2D;

public class ReadSparseMatrix {
	
	public DoubleMatrix2D read(String file){
		ArrayList<Cell> data = new ArrayList<Cell>();
		DoubleMatrix2D matrix = null;
		int maxRow = 0, maxCol = 0;
		try{
			FileInputStream stream = new FileInputStream(file);
			BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
			String line;
			while((line = reader.readLine()) != null){
				String[] values = line.split(" ");
				Cell c = new Cell(values);
				data.add(c);
				if(c.row > maxRow){
					maxRow = c.row;
				}
				if(c.col > maxCol){
					maxCol = c.col;
				}
			}
			reader.close();
			stream.close();
		}catch(IOException e){
			System.err.println("Something went wrong opening " + file);
			e.printStackTrace();
		}catch(NumberFormatException nfe){
			System.err.println("Corrupted file. Only numbers are allowed");
			nfe.printStackTrace();
		}
		if(maxRow > 0 && maxCol > 0){
			matrix = new DenseDoubleMatrix2D(maxRow, maxCol);
			for(Cell c: data){
				matrix.setQuick(c.row-1, c.col-1, c.value);
			}
		}
		System.out.println("Matrix with " + matrix.rows() + " rows and " + matrix.columns() + " columns has been loaded" );
		return matrix;
	}
	
	public ArrayList<SparseVector> readVectors(String file){
		ArrayList<Cell> data = new ArrayList<Cell>();
		data.ensureCapacity(1000);
		ArrayList<SparseVector> vectors = new ArrayList<SparseVector>();
		int currentRow = 1;
		try{
			FileInputStream stream = new FileInputStream(file);
			BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
			String line;
			while((line = reader.readLine()) != null){
				String[] values = line.split(" ");
				Cell c = new Cell(values);
				if(c.row != currentRow){
					SparseVector v = new SparseVector();
					for(Cell d: data){
						v.setQuick(d.col-1, d.value);
					}
					//v.sort();
					vectors.add(v);
					data.clear();
					currentRow = c.row;
				}
				data.add(c);
			}
			reader.close();
			stream.close();
		}catch(IOException e){
			System.err.println("Something went wrong opening " + file);
			e.printStackTrace();
		}catch(NumberFormatException nfe){
			System.err.println("Corrupted file. Only numbers are allowed");
			nfe.printStackTrace();
		}
		SparseVector v = new SparseVector();
		for(Cell d: data){
			v.set(d.col-1, d.value);
		}
		vectors.add(v);
		System.out.println(vectors.size() + " vectors loaded.");
		return vectors;
	}

}

class Cell{	
	int row;
	int col;
	double value;
	
	public Cell(String[] values){
		row = Integer.parseInt(values[0]);
		col = Integer.parseInt(values[1]);
		value = Double.parseDouble(values[2]);
	}
}